﻿#pragma strict
/////////////////////////////////////////////////////////////////////
// BaseCamera的推拉功能.
/////////////////////////////////////////////////////////////////////
var cam:FollowedCamera;

var scrollSpeed:float = 400;
var isScrollReverse:boolean = true;
//推拉距离(摄影机到观察目标点)的范围
var distance:Vector2 = Vector2(4,15);
var rotateX:Vector2 = Vector2(35,45);
var smoothSpeed:float = 0.11;
var smoothRotateSpeed:float = 0.11;

var ratio:float;
var targetPos:Vector3;

private var dollyDir:Vector3;

private var offsetDirNormalized:Vector3;
private var min:Vector3;
private var max:Vector3;
private var minLength:float;
private var maxLength:float;


function Start () {
	cam = GetComponent.<FollowedCamera>();
	targetPos = cam.offsetDir;
}

function Update () {
	Refresh();
	
	Rotate();
	Dolly();
}

function Refresh(){
	offsetDirNormalized = cam.offsetDir.normalized;
	min = offsetDirNormalized * distance.x;
	max = offsetDirNormalized * distance.y;
	minLength = min.magnitude;
	maxLength = max.magnitude;	
}

function Dolly(){
	var v:float = GetInput();
	dollyDir = offsetDirNormalized * v * scrollSpeed * Time.deltaTime;
	
	targetPos += dollyDir;
	ClampTargetPos();
	cam.offsetDir = Vector3.Lerp(cam.offsetDir,targetPos,smoothSpeed);
}

function ClampTargetPos(){
	var m:float = targetPos.magnitude;
	var length:float = (maxLength-minLength);
	ratio = (m-minLength)/length;
	
	var upDot:float = Vector3.Dot(targetPos,min);
	if(upDot > 0){
		if(m > maxLength){
			targetPos = max;
		}else if(m < minLength){
			targetPos = min;
		}
	}else{
		targetPos = min;
	}	
}

function Rotate(){
	var euler = cam.tr.localEulerAngles;
		euler.x = Mathf.LerpAngle(rotateX.x,rotateX.y,ratio);
	cam.tr.localRotation = Quaternion.Slerp(cam.tr.localRotation,Quaternion.Euler(euler),smoothRotateSpeed);
}

function GetInput():float{
	var v = Input.GetAxis("Mouse ScrollWheel");
		v *= isScrollReverse? -1:1;
	return v;
}